﻿using System;

using System.Net;
using System.Web.Script.Serialization;
using System.IO;
using System.Text.RegularExpressions;
using System.Data;


namespace bcse.by.helper
{
	class Program
	{
		static string Notmalize(string str)
		{
			Regex r = new Regex(@"\<.+\>(?<value>.+)\<");
			Match m = r.Match(str);
			if (m.Success)
				str = m.Groups["value"].ToString().Replace("\x00a0", "");
			return str;
		}
		static DataTable RemoveDuplicateRows(DataTable dTable, string colName)
		{
			System.Collections.Hashtable hTable = new System.Collections.Hashtable();
			System.Collections.ArrayList duplicateList = new System.Collections.ArrayList();

			foreach (DataRow drow in dTable.Rows)
			{
				if (hTable.Contains(drow[colName]))
					duplicateList.Add(drow);
				else
					hTable.Add(drow[colName], string.Empty);
			}

			foreach (DataRow dRow in duplicateList)
				dTable.Rows.Remove(dRow);

			return dTable;
		}
		static void Main(string[] args)
		{
			HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("http://www.bcse.by/core/processor.ashx?processor=currency/getauctionstotal&data");


			System.Data.DataTable Table = new System.Data.DataTable();

			try
			{
				using (FileStream File = new FileStream(@"e:\Projects\Lab_CSharp\bcse.by.helper\Table.xml", FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read))
				{
					Table.ReadXml(File);
				}
			}
			catch{ }

			if (string.IsNullOrEmpty(Table.TableName))
			{
				Table.TableName = "BCSE_USD";
				Table.Columns.Add("StartPeriod", typeof(DateTime));
				Table.Columns.Add("EndPeriod", typeof(DateTime));
				Table.Columns.Add("AverageCourse", typeof(ulong));
				Table.Columns.Add("CourseDeviationCurr", typeof(long));
				Table.Columns.Add("DailyDemand", typeof(ulong));
				Table.Columns.Add("DailySupply", typeof(ulong));
				Table.Columns.Add("SumDemand", typeof(ulong));
				Table.Columns.Add("SumSupply", typeof(ulong));
				Table.Columns.Add("StartCourse", typeof(ulong));
				Table.Columns.Add("FinalCourse", typeof(ulong));
				Table.Columns.Add("MaxCourse", typeof(ulong));
				Table.Columns.Add("MinCourse", typeof(ulong));
				Table.Columns.Add("ParticipantNum", typeof(ulong));
				Table.Columns.Add("VolumeAttendedCurr", typeof(ulong));
				Table.Columns.Add("VolumeCurr", typeof(ulong));
			}

			object maxItem = Table.Compute("max(StartPeriod)", string.Empty);
			DateTime lastStart = Convert.ToDateTime(DBNull.Value.Equals(maxItem) ? "2010-01-01T00:00:00.000Z" : maxItem);

			//Our method is post, otherwise the buffer (postvars) would be useless
			Request.Method = "POST";
			//We use form contentType, for the postvars.
			Request.ContentType = "application/json";
			//Our postvars
			//byte[] buffer = System.Text.Encoding.ASCII.GetBytes("{\"startDate\":\"2011-12-31T21:00:00.000Z\",\"endDate\":\"2012-02-16T20:59:59.000Z\",\"discrecity\":\"D\",\"auctionMode\":\"1\",\"needStatistics\":\"1\",\"instrumentIds\":\"\",\"currCodes\":\"1\",\"attendedCurrCodes\":\"\",\"pagesize\":50,\"pageno\":0}");
			string postdata = "{{\"startDate\":\"{0:s}Z\",\"endDate\":\"{1:s}Z\",\"discrecity\":\"D\",\"auctionMode\":\"1\",\"needStatistics\":\"1\",\"instrumentIds\":\"\",\"currCodes\":\"1\",\"attendedCurrCodes\":\"\",\"pagesize\":50,\"pageno\":0}}";
			postdata = string.Format(postdata, lastStart, lastStart.AddDays(7));
			byte[] buffer = System.Text.Encoding.ASCII.GetBytes(postdata);
			//The length of the buffer (postvars) is used as contentlength.
			Request.ContentLength = buffer.Length;
			//We open a stream for writing the postvars
			Stream PostData = Request.GetRequestStream();
			//Now we write, and afterwards, we close. Closing is always important!
			PostData.Write(buffer, 0, buffer.Length);
			PostData.Close();

			Stream stm = Request.GetResponse().GetResponseStream();

			string strContent = new StreamReader(stm).ReadToEnd();

			var jss = new JavaScriptSerializer();
			Object Response = jss.DeserializeObject(strContent);

			Object Result = jss.DeserializeObject((Response as System.Collections.Generic.Dictionary<string, object>)["result"] as string);

			object[] data = (object[])(Result as System.Collections.Generic.Dictionary<string, object>)["data"];

			foreach (System.Collections.Generic.Dictionary<string, object> item in data)
			{
				System.Data.DataRow Row = Table.NewRow();
				foreach (System.Data.DataColumn column in Table.Columns)
				{
					//DateTime Start = new DateTime();
//					Type type = column.DataType;

					System.Reflection.MethodInfo m = column.DataType.GetMethod("Parse", new Type[] { typeof(string) });
					object value = null;
					if (m != null)
					{
						value = m.Invoke(null, new object[] { Notmalize(item[column.ColumnName] as string) });
					}
					else
						value = item[column.ColumnName] as string;
					Row[column] = value;

						//.TryParse(item["StartPeriod"] as string, out Start);
				}
				Table.Rows.Add(Row);

			}

			RemoveDuplicateRows(Table, "StartPeriod");

			using (FileStream File = new FileStream(@"e:\Projects\Lab_CSharp\bcse.by.helper\Table.xml", FileMode.Create, FileAccess.Write, FileShare.Write))
			{
				Table.WriteXml(File, System.Data.XmlWriteMode.WriteSchema, false);
			}

		}
	}
}
